class Solution {
    public boolean isValid(String s) {
        //利用栈去做
        Stack<Character> stack = new Stack<>();
        //遍历字符串中字符
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(ch == '(' || ch == '{' || ch == '['){
                stack.push(ch);
            }else{
                //字符串还没遍历结束时，栈为空说明右括号多
                if(stack.isEmpty()){
                    return false;
                }
                if(ch == ')' && stack.peek() == '('
                || ch == '}' && stack.peek() == '{'
                || ch == ']' && stack.peek() == '['){
                    stack.pop();
                }else{
                    //当左右括号不匹配时返回false
                    return false;
                }
            }
        }
        //字符串已经遍历完，判断栈是否为空，为空则有效，不为空说明括号匹配但是左括号多
        if(stack.isEmpty()){
            return true;
        }
        return false;
    }
}